<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>translate.service - admin</title>
    <link rel="stylesheet" href="./src/css/layui.css">
    <style>
        body {padding: 20px; /*overflow-y: scroll;*/}
        .translate-result-language-text-ul{
            display: grid;
        }
        .translate-result-language-text-item{
            float:left;
            text-align:left;
            display: initial;
        }
        .layui-table-cell{
            overflow: visible;
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
            height: auto !important;
            line-height: normal;
        }
        .layui-table td, .layui-table th {
            height: auto;
        }
        .translate-result-language-text-item span {
            white-space: pre-wrap;
        }
        .layui-laypage>.layui-laypage-limits{
            display:none;
        }
    </style>
</head>
<body>
<!-- 搜索表单 -->
<div class="layui-form" style="padding-bottom: 20px;">
    <input type="text" id="to" name="to" style="display:none;">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">目标域名</label>
            <div class="layui-input-inline">
                <input type="text" id="domain" name="domain" placeholder="请输入目标域名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <a class="layui-btn" href="javascript:;" onclick="searchTranslation();" style="margin-left: 15px;">搜索</a>
            <a class="layui-btn layui-btn-normal" id="addDomainButton" href="javascript:;" onclick="showAddDomainDialog();" style="margin-left: 15px;">添加域名</a>
        </div>
    </div>
</div>

<table class="layui-hide" id="ID-table-demo-data"></table>
<script src="./src/layui.js"></script>
<script src="./translate.service.js"></script>
<script src="./src/msg.js"></script>
<script>
    var domainListData; //当前加载的域名列表数据
    // 清理文本，移除异常字符
    function cleanText(str) {
        if (!str || typeof str !== 'string') {
            return '';
        } else {
            return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, '').trim();
        }
    }
    var tableInstance;
    layui.use(['form', 'table', 'layer', 'jquery'], function(){
        var form = layui.form;
        var table = layui.table;
        var layer = layui.layer;
        var $ = layui.jquery;
        // 监听 postMessage 事件，更新 <span> 并关闭弹窗
        window.addEventListener('message', function(event) {
            try {
                var data = event.data;
                console.log('Received postMessage:', event.data, 'from:', event.origin);
                if (data && data.type == 'updateTranslation') {
                    var spanId = data.id + '_' + data.language;
                    var span = document.getElementById(spanId);
                    if (span) {
                        span.innerHTML = data.text;
                        msg.success('翻译文本更新成功');
                    } else {
                        msg.failure('无法找到对应的翻译文本元素');
                    }
                    var index = layer.getFrameIndex(data.frameName);
                    if (index) {
                        layer.close(index);
                    } else {
                        msg.failure('无法关闭弹窗，索引不存在');
                    }
                }

            } catch (e) {
                console.error('postMessage handler error:', e);
                msg.failure('更新翻译时出错');
            }
        }, false);
        // 搜索功能 - 渲染表格，支持服务器分页
        window.searchTranslation = function () {
            var domainInput = $('#domain').val().trim();
            var to = $('#to').val().trim();
            tableInstance = table.render({
                elem: '#ID-table-demo-data',
                url: domain + 'admin/domain/getDomainList.json',
                method: 'post',
                where: {
                    token: token,
                    domain: domainInput,
                    to: to
                },
                request: {
                    pageName: 'currentPage',
                    limitName: 'everyNumber'
                },
                parseData: function(res) {
                    console.log(res)
                    if (res.result == 1) {
                        domainListData = res.list;
                        let tableData = res.list || [];

                        return {
                            "res":res,
                            "code": 0,
                            "msg": res.info,
                            "count": res.page ? res.page.allRecordNumber : tableData.length,
                            "data": tableData
                        };
                    } else {
                        //msg.failure(res.info || 'API 请求失败');
                        return {
                            "res":res,
                            "code": 1,
                            "msg": res.info || '请求失败',
                            "count": 0,
                            "data": []
                        };
                    }
                },
                cols: [[
                    { field: 'domain', title: '域名', width: '25%', sort: true },
                    { field: 'dayMaxSize', title: '每日翻译上限(字)', width: '20%', templet: function(d){
                            return d.dayMaxSize ? d.dayMaxSize.toLocaleString() : '0';
                        } },
                    { field: 'maxCacheMemorySize', title: '内存缓存大小(字)', width: '20%', templet: function(d){
                            return d.maxCacheMemorySize ? d.maxCacheMemorySize.toLocaleString() : '0';
                        } },
                    { field: 'maxCacheFileSize', title: '文件缓存大小(字)', width: '20%', templet: function(d){
                            return d.maxCacheFileSize ? d.maxCacheFileSize.toLocaleString() : '0';
                        } },
                    { title: '操作', width: '15%', templet: function(d){
                            return '<button class="layui-btn layui-btn layui-btn-xs edit-domain" data-domain="' + d.domain + '">编辑</button>'+
                                '<button class="layui-btn layui-btn-danger layui-btn-xs delete-domain-btn" data-domain="' + d.domain + '">删除</button>';
                        } }
                ]],
                skin: 'line',
                page: true,
                limit: 20,
                limits: [10, 20, 50, 100],
                done: function (res, curr, count) {
                    if(res.res.result == 2){
                        //未登录
                        msg.failure('请先登录', function(){
                            localStorage.removeItem('token');
                            window.top.location.reload();
                        });
                        return;
                    }
                    if (count > 0) {
                        //msg.success('数据加载成功');
                    } else {
                        //msg.failure('暂无数据');
                    }

                    // 动态绑定删除按钮的点击事件
                    $('.delete-domain-btn').off('click').on('click', function() {
                        var $btn = $(this);
                        var domain = $btn.data('domain');
                        deleteDomain(domain);
                    });
                    // 动态绑定编辑按钮的点击事件
                    $('.edit-domain').off('click').on('click', function() {
                        var $btn = $(this);
                        var domain = $btn.data('domain');
                        
                        // 找到对应的域名数据
                        var domainData = domainListData.find(function(item) {
                            return item.domain === domain;
                        });
                        
                        // 将域名数据存储到全局变量，供编辑页面使用
                        window.currentEditDomainData = domainData;
                        
                        layer.open({
                            type: 2,
                            title: '编辑域名',
                            area: ['600px', '500px'],
                            shadeClose: true,
                            content: './domainEdit.html?domain=' + encodeURIComponent(domain)
                        });
                    });
                }
            });
        };
        // 编辑某条翻译的结果
        function editTranslateText(id, language, text, domain) {
            var spanElement = document.getElementById(id + '_' + language);
            var spanText = spanElement ? spanElement.innerHTML : text;
            var data = {
                id: id,
                language: language,
                text: spanText,
                domain: domain
            };
            localStorage.setItem('translateData', JSON.stringify(data));
            layer.open({
                type: 2,
                title: '编辑翻译 【' + language + '】',
                area: ['90%', '90%'],
                shadeClose: true,
                content: './edit-translate-text.html?id=' + encodeURIComponent(id) + '&language=' + encodeURIComponent(language)
            });
        }
        function timestampToTime(timestamp) {
            if (timestamp.toString().length == 10) {
                timestamp = timestamp * 1000;
            }
            var date = new Date(timestamp);
            var Y = date.getFullYear() + "-";
            var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
            var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
            var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
            var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
            var s = (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
            return Y + M + D + h + m + s;
        }
        // 删除域名
        function deleteDomain(domainName) {
            layer.confirm('确定要删除该域名吗？', {icon: 3, title:'提示'}, function(index){
                $.ajax({
                    url: domain + 'admin/domain/deleteDomain.json',
                    type: 'post',
                    data: {
                        token: token,
                        domain: domainName
                    },
                    success: function(res) {
                        if (res.result == 1) {
                            msg.success('删除成功');
                            searchTranslation();
                        } else {
                            msg.failure(res.info || '删除失败');
                        }
                    },
                    error: function() {
                        msg.failure('网络错误，删除失败');
                    }
                });
                layer.close(index);
            });
        }
        // 显示添加域名对话框
        window.showAddDomainDialog = function() {
            layer.open({
                type: 2,
                title: '添加域名',
                area: ['600px', '580px'],
                shadeClose: true,
                content: './add-domain.html'
            });
        }
        searchTranslation();
    });

</script>

</body>
</html>